package ru.nsu.ccfit.shumkina.algorithm.adaptation.profitcounter;

import ru.nsu.ccfit.shumkina.algorithm.adaptation.Path;
import ru.nsu.ccfit.shumkina.algorithm.adaptation.UsedPathsInfo;
import ru.nsu.ccfit.shumkina.algorithm.graphworks.Graph;

import java.util.ArrayList;
import java.util.Map;
import java.util.TreeMap;

/**
 * Created with IntelliJ IDEA.
 * User: vera
 * Date: 5/15/13
 * Time: 4:56 PM
 * To change this template use File | Settings | File Templates.
 */
public class ProfitBasedOnUsedPathsInfo {
    public static Profit countProfitInfoAndAdaptedPaths(TreeMap<String, UsedPathsInfo> usedPaths, Graph original,
                                                        Graph adapted, TreeMap<String, String> acceptedAdaptations) {
        Integer movesCountOriginal = 0;
        Integer savedMoves = 0;
        // get list of adapted subpaths
        TreeMap<String, ArrayList<String>> adaptedSubpaths = new TreeMap<String, ArrayList<String>>();
        for(Map.Entry<String, String> entry: acceptedAdaptations.entrySet())
        {
            String[] arcs = entry.getKey().split(" -> ");
            ArrayList<String> prevPath = UtilityFunctions.findShortestPath(arcs[0], arcs[1], original, 10);
            adaptedSubpaths.put(entry.getKey(), prevPath);
        }
        Profit p = new Profit();
        p.adaptedSubpaths = adaptedSubpaths;
        // fill adapted paths in UsedPathsInfoStructure
        for (Map.Entry<String, UsedPathsInfo> entry: usedPaths.entrySet())
        {
            for (Map.Entry<String, Path> pathEntry: entry.getValue().paths.entrySet())
            {
                if (pathEntry.getValue().path.size() >= 20)
                    System.out.print("Note: current path is too long. It may hang profit counter. \n");
                pathEntry.getValue().adaptedPath = UtilityFunctions.findShortestPath(entry.getKey(),
                        pathEntry.getKey(), adapted, pathEntry.getValue().path.size());

                movesCountOriginal += pathEntry.getValue().path.size()*pathEntry.getValue().useCount;
                Integer curProfit = (pathEntry.getValue().path.size()
                        - pathEntry.getValue().adaptedPath.size())*pathEntry.getValue().useCount;

                if (curProfit < 0)
                    System.out.print("Profit<0. This should not happen for now!");
                savedMoves += curProfit;
            }
        }
        p.allMoves = movesCountOriginal;
        p.savedMoves = savedMoves;
        return p;
    }
}
